local socket = require "socket"
local blaze = require "blaze"
local app = require "app"
local game = app.game.running

local M = {}

M.state = {
    last_send_at = -1,
    shortcut_index = 0,
    messages = {
        -- {
        --     sender = {
        --         user_id = 1,
        --     },
        --     msg_type = 1,
        --     text = "纯文本聊天"
        -- },
        -- {
        --     sender = {
        --         user_id = 1,
        --     },
        --     msg_type = 2,
        --     emoji_id = 1
        -- }
    }
}

M.getters = {
    -- 获取表示下次可以说话的剩余时间（单位：秒）
    cooldown = function(state)
        local elasped = socket.gettime() - state.last_send_at
        return math.max(2 - elasped, 0)
    end
}

local function say(msg_type, text)
    local player = blaze.kbe.player()
    if not player or not player.chat then
        return
    end
    player.chat:say(msg_type, text)
end

M.mutations = {
    say_text = function(store, state, args)
        local text = args
        say(game.chat.MSG_TYPE_TEXT, text)
    end,

    say_phrase = function(store, state, args)
        local id = args
        say(game.chat.MSG_TYPE_PHRASE, tostring(id))
    end,

    say_emoji = function(store, state, args)
        local id = args
        say(game.chat.MSG_TYPE_EMOJI, tostring(id))
    end,

    new_message = function(store, state, args)
        local msg = args
        if msg.sender then
            local player = blaze.kbe.player()
            if player and player.user_id == msg.sender.user_id then
                msg.from_self = true
            end
        end
        table.insert(state.messages, msg)
        store.emit("收到聊天消息", msg)
    end,

    clear = function(store, state, args)
        state.messages = {}
        store.emit("清空")
    end,

    set_shortcut_index = function(store, state, args)
        state.shortcut_index = args
        store.emit("快捷聊天切页")
    end
}

return M